const http = require("http");
const url = require("url");


const dealRequest = (req, res) => {
    res.setHeader("Content-type","application/json");
    const path = url.parse(req.url, true);
    const pathname = path.pathname;
    const method = req.method;
    console.log(method, pathname);
    // 处理跨域
    res.setHeader("Access-Control-Allow-Origin", '*');
    res.setHeader("Access-Control-Allow-Headers", "x-requested-with,Authorization,token, content-type");
    res.setHeader("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    // 对跨域下的多发的 OPTIONS 请求进行处理
    if (req.method === "OPTIONS") { // CORS
        res.statusCode = 200;
        res.end();
    }
    if(pathname === "/api/testError" && method.toLowerCase() === "get") {
        const timer = setTimeout(() => {
            res.write(JSON.stringify({
                error: "error",
            }));
            res.end();
            clearInterval(timer);
        }, 10000);
    }
};

const server = http.createServer(dealRequest);

server.listen(3006, 'localhost');